<?php

namespace app\admin\controller;

use app\helpers\Common;

use think\Request;

class Article extends Base
{
    public function initialize()
    {
        parent::initialize();

        $this->defaultWhere = [
            ['status', '<>', config('constants.SOFT_DELETE_STATUS')]
        ];
        $this->defaultOrder = 'created_at DESC';
    }

    /**
     * 回收站
     */
    public function recyclebin(Request $request)
    {
        $this->indexView = 'recyclebin';
        $this->defaultWhere = [
            ['status', '=', config('constants.SOFT_DELETE_STATUS')]
        ];
        $this->defaultOrder = 'created_at DESC';

        return parent::index($request);
    }

    /**
     * 还原
     */
    public function restore(Request $request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
        $model = new $className;

        $id = $request->param('id');
        $data = [
            'status' => 1,
            'deleted_id' => 0,
            'deleted_at' => 0
        ];
        $result = $model->where('id', $id)->update($data);
        if ($result === false) {
            return $this->error('还原失败!', (string)url('admin/' . $this->model . '/index'));
        }

        // 写入日志
        $content = '还原了一条' . __($this->model) . '数据。';
        $logRes = Common::actionLog($request, $this->admin['id'], $content, $id, json_encode([$data]));

        return $this->success('还原成功!', (string)url('admin/' . $this->model . '/index'));
    }

    /**
     * 彻底删除
     */
    public function clean(Request $request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
        $model = new $className;

        $id = $request->param('id');
        $result = $model->where('id', $id)->delete();
        if ($result !== false) {
            return $this->error('彻底删除失败!', (string)url('admin/' . $this->model . '/index'));
        }

        // 写入日志
        $content = '彻底删除了一条' . __($this->model) . '数据。';
        $logRes = Common::actionLog($request, $this->admin['id'], $content, $id, '');

        return $this->success('彻底删除成功!', (string)url('admin/' . $this->model . '/index'));
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request)
    {
        $param = $request->param();
        $where = [];
        if (isset($param['title']) && $param['title']) {
            $where[] = ['title', 'like', '%' . trim($param['title']) . '%'];
        }
        if (isset($param['range_date']) && $param['range_date']) {
            $rangeDate = explode(' ~ ', $param['range_date']);
            $startTime = strtotime($rangeDate[0]);
            $endTime = strtotime($rangeDate[1]);
            $where[] = ['created_at', '>=', $startTime];
            $where[] = ['created_at', '<=', $endTime];
        }

        return $where;
    }
}